<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Service\NetworkQuery;
use App\Http\Requests\Admin\Service\QueryResource;
use App\Http\Requests\Admin\Service\ShowRequest;
use App\Http\Requests\Admin\Service\ServiceCreate;
use App\Http\Requests\Admin\Service\ServiceUpdate;
use App\Http\Requests\Admin\Service\ServiceDestroy;
use App\Models\AdminUser;
use App\Models\NetworkExpress;
use App\Models\PrivilegeStation;
use App\Models\Service;
use App\Repositories\ServiceRepository;
use App\Repositories\UserLogRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ServiceController extends Controller
{
    //默认密码
    const BASE_PASSWORD = '123456';
    protected $serviceRepository;
    protected $userLogRepository;

    /**
     * ServicesController constructor.
     * @param ServiceRepository $serviceRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        ServiceRepository $serviceRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->serviceRepository = $serviceRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取服务站列表资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function index(QueryResource $request)
    {
        $service_name = $request->get('service_name', false);
        $owner_name = $request->get('owner_name', false);
        $status = $request->get('status', false);
        $limit = $request->get('paginate', 15);
        $server_id = $request->get('server_id', false);
        if ($status === null) {
            $status = false;
        }
        if ($service_name === null) {
            $service_name = false;
        }
        if ($owner_name === null) {
            $owner_name = false;
        }
        if ($server_id === null) {
            $server_id = false;
        }
        $services = $this->serviceRepository->getServices($service_name, $limit, $owner_name, $status, $server_id);
        return success($services);
    }

    /**
     * 获取服务站详情
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ShowRequest $request
     * @param $station
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(ShowRequest $request, $station)
    {
        $services = $this->serviceRepository->getServiceDetails($station);
        if (optional($services)->scope) {
            $services->scope = json_decode($services->scope, true);
        }
        return success($services);
    }


    /**
     * 创建服务站
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ServiceCreate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function store(ServiceCreate $request)
    {
        $attributes = $this->extractInputFromRules($request, $request->rules());
        if (array_key_exists('scope', $attributes) && $attributes['scope']) {
            $attributes['scope'] = json_encode($attributes['scope'], true);
        }
        if ($attributes['is_child'] == 0) {
            $attributes['pid'] = 0;
        } else {
            $service = Service::query()->where('id', '=', $attributes['pid'])->first();
            if ($service) {
                $attributes['bank_card'] = $service->$service;
            } else {
                return failed('找不到该在服务站', 422);
            }
        }
        DB::beginTransaction();
        try {
            $password = $request->password;
            unset($attributes['password']);
            $services = $this->serviceRepository->create($attributes);
            //创建网点管理员账户
            $adminUser = new AdminUser();
            $adminUser->name = $request->name;
            $adminUser->phone = $request->phone;
            $adminUser->password = $password;
            $adminUser->service_id = $services->id;
            $adminUser->is_owner = 1;//店长
            $adminUser->save();
            //添加所有权限
            $ids = PrivilegeStation::select(['id'])->get()->toArray();
            $privilege_ids = [];
            if (is_array($ids) && count($ids)) {
                foreach ($ids as $id)
                    $privilege_ids[] = $id['id'];
            }
            if (is_array($privilege_ids) && count($privilege_ids)) {
                $adminUser->privileges()->attach($privilege_ids);
            }
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = $services->id;
        $name = $admin->name;
        $operation = '创建了站点[' . $services->designation . ']';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return stored($services);
    }

    /**
     * 更新服务站资源
     *
     * Date: 2018/05/11
     * @author Tenny
     * @param ServiceUpdate $request
     * @param Service $station
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function update(ServiceUpdate $request, Service $station)
    {
        $servicesAttr = array_filter($request->only([
            'designation',
            'name',
            'phone',
            'status',
            'province_id',
            'city_id',
            'district_id',
            'address',
            'start_time',
            'end_time',
            'service_img',
            'bank_card',
            'scope',
            'zoom',
        ]), function ($value) {
            if ($value === null || $value === '') {
                return false;
            } else {
                return true;
            }
        });
        if (array_key_exists('scope', $servicesAttr) && $servicesAttr['scope']) {
            $servicesAttr['scope'] = json_encode($servicesAttr['scope'], true);
        }
        $station->update($servicesAttr);
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = $station->id;
        $name = $admin->name;
        $operation = '更新了[' . $station->designation . ']';
        $history = json_encode($station->toArray(), true);
        $actuality = json_encode($servicesAttr, true);
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        //返回站点列表所需参数
        $result = Service::where('id', '=', $station->id)
            ->withCount(["couriers", "networks", "childServices"])
            ->first();
        return updated($result);
    }

    /**
     * 删除 服务站 资源
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param ServiceDestroy $request
     * @param Service $station
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(ServiceDestroy $request, Service $station)
    {
        DB::beginTransaction();
        try {
            //删除管理员
            AdminUser::where('service_id', '=', $station->id)->delete();
            $station->childServices()->delete();
            $station->networks()->detach();
            $station->couriers()->delete();
            $station->delete();
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = $station->id;
        $name = $admin->name;
        $operation = '删除了站点[' . $station->designation . ']';
        $history = null;
        $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 获取关联网点
     *
     * Date: 2018/06/12
     * @author Tenny
     * @param NetworkQuery $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function relationStation(NetworkQuery $request)
    {
        $limit = $request->get('paginate', false);
        $service_id = $request->get('service_id', false);
        if ($limit == null) {
            $limit = false;
        }
        if ($service_id == null || $service_id == false) {
            return failed('请上传服务站id', 422);
        }
        $networks = $this->serviceRepository->getRelationNetworks($service_id, $limit);
        return success($networks);
    }

    /**
     * 解除关联网点
     *
     * Date: 2018/05/09
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroyRelation(Request $request)
    {
        $relation_id = $request->get('id', false);
        $networkExpress = NetworkExpress::where('id', '=', $relation_id)->with(['services', 'network'])->first();
        if (!$networkExpress) {
            return failed('该关联关系不存在', 400);
        }
        $force = $request->get('force');
        $force ? $networkExpress->delete() : $networkExpress->forceDelete();
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = $networkExpress->service_id;
        $name = $admin->name;
        $operation = '解除除了[' . $networkExpress->services->designation . ']与网点[' . $networkExpress->network->designation . ']的关联';
        $history = null;
        $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return deleted();
    }

    /**
     * 获取服务站子站点列表资源列表
     *
     * Date: 2018/05/10
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function childStation(QueryResource $request)
    {
        $service_id = $request->get('service_id', false);
        $limit = $request->get('paginate', 15);
        $services = $this->serviceRepository->getChildServices($service_id, $limit);
        return success($services);
    }

    /**
     * 重置站点负责人密码
     *
     * Date: 2018/06/15
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function password(Request $request)
    {
        $params = $this->validate($request, [
            'service_id' => 'required',
        ], [
            'service_id.required' => '请上传站点id',
        ]);
        $service = Service::where('id', '=', $params['service_id'])->first();
        if ($service->phone) {
            $adminUser = AdminUser::where('service_id', '=', $params['service_id'])
                ->where('phone', '=', $service->phone)
                ->first();
            if ($adminUser) {
                $adminUser->password = self::BASE_PASSWORD;
                $adminUser->save();
            } else {
                return failed('找不到该站点管理员资源', 400);
            }
        } else {
            return failed('找不到该站点', 400);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = $params['service_id'];
        $name = $admin->name;
        $operation = '重置了站点[' . $service->designation . ']的负责人[' . $adminUser->id . ']密码';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return updated([], '该站点的密码重置成功');
    }

    /**
     * 地图搜索功能
     *
     * Date: 2018/06/15
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function search(Request $request)
    {
        $keyword = $request->get('keyword', false);
        $region = $request->get('region', false);
        if ($keyword === null) {
            $keyword = false;
        }
        if ($region === null) {
            $region = false;
        }
        $result = $this->serviceRepository->search($keyword, $region);
        return success($result);
    }

    /**
     * 检测手机号码是否存在
     *
     * Date: 2018/06/10
     * @author Tenny
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function existence(Request $request)
    {
        $this->validate($request, [
            'phone' => ['required', 'regex:/^(1[3456789])\d{9}$/', 'unique:service,phone']
        ], [
            'phone.required' => '请输入手机号码',
            'phone.regex' => '您输入的手机号码有误',
            'phone.unique' => '您输入的手机号码已存在'
        ]);
        return message('可以注册');
    }

    /**
     * 获取服务站列表资源列表
     *
     * Date: 2018/07/25
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function parentStation(QueryResource $request)
    {
        $services = $this->serviceRepository->getParentStation();
        return success($services);
    }
}
